package com.handpay.zztong.hp.accountcenter.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.SwipeCard;
import com.handpay.zztong.hp.accountcenter.model.uploadcheckinfo.UploadCheckInfoModel;
import com.handpay.zztong.hp.adapter.BankAdapter;
import com.handpay.zztong.hp.adapter.ProvinceAdapter;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.model.banklist.Bank;
import com.handpay.zztong.hp.base.model.banklist.BankProvince;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.BankArea;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.activity.RegisterResultActivity;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.protocol.CardProtocolKey;
import com.handpay.zztong.hp.protocol.UCProtocolKey;
import com.handpay.zztong.hp.ui.HPBankAreaEditView;
import com.handpay.zztong.hp.ui.HPSubBankEditView;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 资质提交
 *
 * @author fplei
 */
public class BaseInfoEditorActivity extends ZZTongActivity implements HPSubBankEditView.OnBankLisenter, HPBankAreaEditView.OnBankAreaLisenter {
    private final String TAG = BaseInfoEditorActivity.class.getSimpleName();
    // 用于表示
    private final String KEY_BANKNAME_BACKUP = "bank_name_backup";
    private final String KEY_BANKAREA_BACKUP = "bank_area_backup";
    final static String KEY_BANKPROVINCENAME_BACKUP = "bank_province_name_backup";
    private EditText mName;
    private EditText mCertNo;
    private EditText mShopName;
    private Spinner mMainSpinner, mProvincesFlagSpinner;
    private HPSubBankEditView mSubBank;
    private HPBankAreaEditView mAreaFlag;
    private EditText mCardNo;
    private Bank mMainBank = null;
    private Bank mSubSelectedBank = null;
    private BankAdapter mMainAdapter;
    private ProvinceAdapter mProvinceAdapter;
    private BankProvince mBankProvince = null;
    private View open_provinces_line, open_areaflag_line, open_subbank_line;
    private BankArea mSelectBankArea = null;
    private View mProvinceTable, mAreaTable, mSubBankTable;
    private static final int REQUEST_CARD = 1;
    private int swiperType = ZZTConstant.SWIPER_GOTO_SWIPERCARD;
    private TextWatcher mTextWatch = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            if (mMainBank.getSubBankFlag().equals("1") && (null == mMainBank || Bank.INVALID_BANK_CODE == mMainBank.getBankCode())) {
                String title = BaseInfoEditorActivity.this.getString(R.string.tip);
                String message = BaseInfoEditorActivity.this.getString(R.string.select_bank_tip);
                BaseInfoEditorActivity.this.showAlertDialog(BaseInfoEditorActivity.this, title, message);
            } else {
                refreshHandler.removeMessages(HANDLER_MSG_TYPE_QUERY_SUBBANKLIST);
                Message msg = refreshHandler.obtainMessage();
                msg.what = HANDLER_MSG_TYPE_QUERY_SUBBANKLIST;
                msg.obj = s.toString();
                refreshHandler.sendMessageDelayed(msg, 1000);
            }
        }
    };
    private TextWatcher mBankAreaTextWatch = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            HPLog.e("jjyang", "area" + mMainBank.getProvinceFlag());
            if (mMainBank.getProvinceFlag().equals("1") && (null == mBankProvince || TextUtils.isEmpty(mBankProvince.getBankProvinceId()))) {
                String title = BaseInfoEditorActivity.this.getString(R.string.tip);
                String message = BaseInfoEditorActivity.this.getString(R.string.select_Province_tip);
                BaseInfoEditorActivity.this.showAlertDialog(BaseInfoEditorActivity.this, title, message);
            } else {
                refreshHandler.removeMessages(HANDLER_MSG_TYPE_QUERY_BANKAREALIST);
                Message msg = refreshHandler.obtainMessage();
                msg.what = HANDLER_MSG_TYPE_QUERY_BANKAREALIST;
                msg.obj = "";//空字符代表返回省下面的全部城市
                refreshHandler.sendMessageDelayed(msg, 1000);

            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        mSubBank.onStop();
    }

    private final static int HANDLER_MSG_TYPE_QUERY_SUBBANKLIST = 1001;
    private final static int HANDLER_MSG_TYPE_QUERY_BANKAREALIST = 1002;
    private RefreshHandler refreshHandler;

    private static class RefreshHandler extends Handler {

        private WeakReference<BaseInfoEditorActivity> mActivity;

        private RefreshHandler(BaseInfoEditorActivity mActivity) {
            this.mActivity = new WeakReference<BaseInfoEditorActivity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_MSG_TYPE_QUERY_SUBBANKLIST: {
                    String s = (String) msg.obj;
                    if (null != s) s = s.trim();
                    BaseInfoEditorActivity activity = mActivity.get();
                    if (null != activity && !TextUtils.isEmpty(s)) {
                        activity.querySubBankList(activity.mMainBank.getBankCode(), s);
                    }
                    break;
                }
                case HANDLER_MSG_TYPE_QUERY_BANKAREALIST: {
                    String area = (String) msg.obj;
                    if (null != area) area = area.trim();
                    BaseInfoEditorActivity activity = mActivity.get();
                    HPLog.i("tag-getBankCode", activity.mMainBank.getBankCode());
                    HPLog.i("tag-bankproviceId", String.valueOf(activity.mBankProvince.getBankProvinceId()));
                    if (null != activity) {
                        if (null != activity.mBankProvince) {
                            activity.queryAreaFlag(activity.mMainBank.getBankCode(), area, String.valueOf(activity.mBankProvince.getBankProvinceId()));
                        } else {
                            activity.queryAreaFlag(activity.mMainBank.getBankCode(), area, null);
                        }
                    }
                    break;
                }
                default:
                    break;
            }

        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_base_info_editor);
        super.onCreate(savedInstanceState);
        mName = (EditText) this.findViewById(R.id.name);
//        mName.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                String text = s.toString();
//                if (text != null && text.length() > 0) {
//                    if (text.length() == 1) {
//                        if (!isLetter(text) && !ischainse(text)) {
//                            s.delete(0, 1);
//                        }
//                    } else {
//                        String newText = text.substring(text.length() - 1, text.length());
//                        if (!isLetter(newText) && !ischainse(newText)) {
//                            s.delete(text.length() - 1, text.length());
//                        }
//                    }
//                }
//            }
//        });
        mCertNo = (EditText) this.findViewById(R.id.certNo);
        mShopName = (EditText) this.findViewById(R.id.shop_name);
//        mShopName.addTextChangedListener(new TextWatcher() {
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int arg1, int arg2, int arg3) {
//
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int arg1, int arg2, int arg3) {
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//                String text = editable.toString();
//                if (text != null && text.length() > 0) {
//                    if (text.length() == 1) {
//                        if (!ischainse(text) && !isNumble(text) && !isLetter(text)) {
//                            editable.delete(0, 1);
//                        }
//                    } else {
//                        String newText = text.substring(text.length() - 1, text.length());
//                        if (!ischainse(newText) && !isNumble(newText) && !isLetter(newText)) {
//                            editable.delete(text.length() - 1, text.length());
//                        }
//                    }
//                }
//            }
//        });
        mMainSpinner = (Spinner) this.findViewById(R.id.main_bank_spinner);
        mProvincesFlagSpinner = (Spinner) this.findViewById(R.id.opening_provinces_spinner);
        mAreaFlag = (HPBankAreaEditView) this.findViewById(R.id.opening_city_edit);
        mSubBank = (HPSubBankEditView) this.findViewById(R.id.sub_bank);
        mCardNo = (EditText) this.findViewById(R.id.card_no);
        mProvinceTable = this.findViewById(R.id.opening_provinces);
        mAreaTable = this.findViewById(R.id.opening_city_view);
        mSubBankTable = this.findViewById(R.id.opening_sub_bank);
        open_provinces_line = this.findViewById(R.id.opening_provinces_line);
        open_areaflag_line = this.findViewById(R.id.opening_city_line);
        open_subbank_line = this.findViewById(R.id.opening_sub_bank_line);

        if (null != getIntent() && ZZTConstant.RECOMPOSE_ACTION.equals(getIntent().getAction())) {
            this.findViewById(R.id.reupload_warning).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.tv_failDes)).setText(AccountUtils.getAccountFailDes(this));
            autoFill();
        } else {
            this.findViewById(R.id.reupload_warning).setVisibility(View.GONE);
            // 第一次提交资质，不显示刷卡
            findViewById(R.id.swipeCard).setVisibility(View.GONE);
        }
        this.findViewById(R.id.nextButton).setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这个时候，也需要检测刷卡器必须插入且可用
                swiperType = ZZTConstant.SWIPER_GOTO_OTHER;
                if (checkField() && checkSwiperOk(BaseInfoEditorActivity.this, true)) {
                    String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
                    if (!TextUtils.isEmpty(address)) {
                        doPostUploadCheckInfo();
                    } else {
                        getCurrentLocation();
                    }
                }
            }
        }));
        mMainAdapter = new BankAdapter(this);
        mMainSpinner.setAdapter(mMainAdapter);
        mMainSpinner.setOnItemSelectedListener(mSelectedListener);

        mProvinceAdapter = new ProvinceAdapter(this);
        mProvincesFlagSpinner.setAdapter(mProvinceAdapter);
        mProvincesFlagSpinner.setOnItemSelectedListener(mSelectedProvinceListener);

        mAreaFlag.addTextChangedListener(mBankAreaTextWatch);
        mAreaFlag.setLisenter(this);

        mSubBank.addTextChangedListener(mTextWatch);
        mSubBank.setLisenter(this);
        refreshHandler = new RefreshHandler(this);
        findViewById(R.id.swipeCard).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                swiperType = ZZTConstant.SWIPER_GOTO_SWIPERCARD;
                goToVPos();
            }
        });
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.compose_base_info_title), true);
    }

    private OnItemSelectedListener mSelectedListener = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            mMainBank = (Bank) parent.getAdapter().getItem(position);
            if (mMainBank.getProvinceFlag().equals("1")) {
                mProvinceTable.setVisibility(View.VISIBLE);
                open_provinces_line.setVisibility(View.VISIBLE);
                queryBankProvinceFlag(mMainBank.getBankCode());
            } else {
                mBankProvince = null;
                mProvinceTable.setVisibility(View.GONE);
                open_provinces_line.setVisibility(View.GONE);
            }
            if (mMainBank.getAreaFlag().equals("1")) {
                mAreaTable.setVisibility(View.VISIBLE);
                open_areaflag_line.setVisibility(View.VISIBLE);
            } else {
                clearBankAreaInfo();
                mAreaTable.setVisibility(View.GONE);
                open_areaflag_line.setVisibility(View.GONE);
            }
            if (mMainBank.getSubBankFlag().equals("1")) {
                mSubBankTable.setVisibility(View.VISIBLE);
                open_subbank_line.setVisibility(View.VISIBLE);
            } else {
                clearSubBankInfo();
                mSubBankTable.setVisibility(View.GONE);
                open_subbank_line.setVisibility(View.GONE);
            }
            Intent i = getIntent();
            String bankNameBackup = i.getStringExtra(KEY_BANKNAME_BACKUP);
            // 如果是重新提交，第一次进入该函数，bankNameBackup不为空，不用清空支行和城市信息;否则需要清空。
            if (!TextUtils.isEmpty(bankNameBackup)) {
                i.putExtra(KEY_BANKNAME_BACKUP, "");
            } else {
                clearSubBankInfo();
                mBankProvince = null;
            }
            String bankAreaName = i.getStringExtra(KEY_BANKAREA_BACKUP);
            HPLog.e("------", "==bankAreaName===" + bankAreaName);
            if (!TextUtils.isEmpty(bankAreaName)) {
                i.putExtra(KEY_BANKAREA_BACKUP, "");
            } else {
                clearBankAreaInfo();
                mBankProvince = null;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            mMainBank = null;
            mBankProvince = null;
            mSelectBankArea = null;
            clearSubBankInfo();
            clearBankAreaInfo();
        }
    };

    private void clearSubBankInfo() {
        mSubBank.removeTextChangedListener(mTextWatch);
        mSubBank.setText("");
        mSubSelectedBank = null;
        mSubBank.addTextChangedListener(mTextWatch);
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    private OnItemSelectedListener mSelectedProvinceListener = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            mBankProvince = (BankProvince) parent.getAdapter().getItem(position);

            Intent i = getIntent();
            String bankProvinceName = i.getStringExtra(KEY_BANKPROVINCENAME_BACKUP);
            if ("1".equals(mMainBank.getProvinceFlag())) {
                //发送消息获取省份下的所有城市
                refreshHandler.removeMessages(HANDLER_MSG_TYPE_QUERY_BANKAREALIST);
                Message msg = refreshHandler.obtainMessage();
                msg.what = HANDLER_MSG_TYPE_QUERY_BANKAREALIST;
                msg.obj = "";//空字符代表返回省下面的全部城市
                refreshHandler.sendMessageDelayed(msg, 1000);
            }

            if (!TextUtils.isEmpty(bankProvinceName)) {
                i.putExtra(KEY_BANKPROVINCENAME_BACKUP, "");
            } else {
                clearBankAreaInfo();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            mSelectBankArea = null;
            clearBankAreaInfo();
        }
    };

    private void clearBankAreaInfo() {
        mAreaFlag.removeTextChangedListener(mBankAreaTextWatch);
        mAreaFlag.setText("");
        mSelectBankArea = null;
        mAreaFlag.addTextChangedListener(mBankAreaTextWatch);
    }

    /**
     * 发送数据到后台，请求验证
     *
     * @return
     */
    private boolean doPostUploadCheckInfo() {
        Hashtable<String, String> paramers = new Hashtable<String, String>();
        String phone = AccountUtils.getAccountPhone(this);
        if (TextUtils.isEmpty(phone)) {
            HPLog.e(TAG, "phone null");
            return false;
        }
        String name = mName.getText().toString().trim();
        String certNo = mCertNo.getText().toString().trim();
        String shopName = mShopName.getText().toString().trim();
        String cardNo = mCardNo.getText().toString();
        cardNo = cardNo.replace(" ", "");
        String bankCode = mMainBank.getBankCode();
        String subBankCode = null;
        if (null != mSubSelectedBank) {
            subBankCode = mSubSelectedBank.getBankCode();
        }
        String provinceId = null;
        if (null != mBankProvince) {
            provinceId = String.valueOf(mBankProvince.getBankProvinceId());
        }
        String areaId = null;
        if (null != mSelectBankArea) {
            areaId = String.valueOf(mSelectBankArea.getBankAreaId());
        }
        String channel = ClientEngine.CHANNEL;
        // 0表示检查
        String type = UCProtocolKey.TYPE_CHECK;
        paramers.put(UCProtocolKey.PHONE, SecureManager.getInstance().des(phone, 1, null));
        paramers.put(UCProtocolKey.KEY_NAME, SecureManager.getInstance().des(name, 1, null));
        paramers.put(UCProtocolKey.KEY_CERTNO, SecureManager.getInstance().des(certNo, 1, null));
        paramers.put(UCProtocolKey.KEY_SHOPNAME, SecureManager.getInstance().des(shopName, 1, null));
        paramers.put(UCProtocolKey.KEY_CARDNUM, SecureManager.getInstance().des(cardNo, 1, null));
        paramers.put(UCProtocolKey.KEY_BANKCODE, bankCode);
        if (!TextUtils.isEmpty(subBankCode)) {
            paramers.put(UCProtocolKey.KEY_SUBBANKCODE, subBankCode);
        }
        if (!TextUtils.isEmpty(provinceId)) {
            paramers.put(UCProtocolKey.KEY_PROVIVCEID, provinceId);
        }
        if (!TextUtils.isEmpty(areaId)) {
            paramers.put(UCProtocolKey.KEY_AREAID, areaId);
        }
        paramers.put(UCProtocolKey.CHANNEL, channel);
        paramers.put(UCProtocolKey.KEY_TYPE, type);
        String mCsn = getCSN();
        paramers.put(CardProtocolKey.CSN_KEY, SecureManager.getInstance().des(mCsn, 1, null));
        appendAddresses(paramers, true);
        paramers.put(BaseProtocolKey.NEWBANKFLAG, newBankFlag);
//        this.doJsonPost(this, Do_UploadCheckInfo, ResponseBean.class, p);
        new UploadCheckInfoModel().doUploadCheckInfoPost(this, paramers, new BusinessEngineListener<ResponseBean>() {
            @Override
            public void callbackBusinessResponse(ResponseBean bean) {
                // 检测成功，通过，进入下一个界面
                // 复用上一层发过来的Intent
                Intent prepareImage = getIntent();
                prepareImage.setAction(null);
                prepareImage.setClass(BaseInfoEditorActivity.this, BaseInfoPrepareImageActivity.class);
                // 通过intent把这边填写的数据传到下一个activity。并且，需要注意，如果这个activity被杀死，应该要恢复其中的数据。
                // 还应该要把之前activity传过来的数据，传到下一个activity
                String name = mName.getText().toString();
                String certNo = mCertNo.getText().toString().trim();
                String shopName = mShopName.getText().toString();
                String cardNo = mCardNo.getText().toString();
                cardNo = cardNo.replace(" ", "");
                String bankCode = mMainBank.getBankCode();
                String subBankCode = null;
                String subBankName = null;
                if (null != mSubSelectedBank) {
                    subBankCode = mSubSelectedBank.getBankCode();
                    subBankName = mSubSelectedBank.getBankName();
                }
                String provinceId = null;
                String provinceName = null;
                if (null != mBankProvince) {
                    provinceId = String.valueOf(mBankProvince.getBankProvinceId());
                    provinceName = mBankProvince.getBankProvinceName();
                }
                String areaId = null;
                String areaName = null;
                if (null != mSelectBankArea) {
                    areaId = String.valueOf(mSelectBankArea.getBankAreaId());
                    areaName = mSelectBankArea.getBankAreaName();
                }
                String areaNameText = mAreaFlag.getText().toString();
                String subBankNameText = mSubBank.getText().toString();
                prepareImage.putExtra(UCProtocolKey.KEY_NAME, name);
                prepareImage.putExtra(UCProtocolKey.KEY_CERTNO, certNo);
                prepareImage.putExtra(UCProtocolKey.KEY_SHOPNAME, shopName);
                prepareImage.putExtra(UCProtocolKey.KEY_CARDNUM, cardNo);
                prepareImage.putExtra(UCProtocolKey.KEY_BANKCODE, bankCode);
                prepareImage.putExtra(UCProtocolKey.KEY_BANKNAME, mMainBank.getBankName());
                if (mMainBank.getProvinceFlag().equals("1")) {
                    prepareImage.putExtra(UCProtocolKey.KEY_PROVINCENAME, mBankProvince.getBankProvinceName());
                    prepareImage.putExtra(UCProtocolKey.KEY_PROVIVCEID, provinceId);
                } else {
                    prepareImage.putExtra(UCProtocolKey.KEY_PROVINCENAME, "");
                    prepareImage.putExtra(UCProtocolKey.KEY_PROVIVCEID, "");
                }
                if (mMainBank.getAreaFlag().equals("1")) {
                    prepareImage.putExtra(UCProtocolKey.KEY_AREAID, areaId);
                    prepareImage.putExtra(UCProtocolKey.KEY_AREANAME, areaNameText);
                } else {
                    prepareImage.putExtra(UCProtocolKey.KEY_AREAID, "");
                    prepareImage.putExtra(UCProtocolKey.KEY_AREANAME, "");
                }
                if (mMainBank.getSubBankFlag().equals("1")) {
                    prepareImage.putExtra(UCProtocolKey.KEY_SUBBANKCODE, subBankCode);
                    prepareImage.putExtra(UCProtocolKey.KEY_SUBBANKNAME, subBankNameText);
                } else {
                    prepareImage.putExtra(UCProtocolKey.KEY_SUBBANKCODE, "");
                    prepareImage.putExtra(UCProtocolKey.KEY_SUBBANKNAME, "");
                }
                startActivity(prepareImage);
            }
        });

        return true;
    }




    /**
     * 根据传入的数据，自动填入表格
     */
    private void autoFill() {
        Intent i = getIntent();
        String name = i.getStringExtra(UCProtocolKey.KEY_NAME);
        String certNo = i.getStringExtra(UCProtocolKey.KEY_CERTNO);
        String shopName = i.getStringExtra(UCProtocolKey.KEY_SHOPNAME);
        mName.setText(name);
        mCertNo.setText(certNo);
        mShopName.setText(shopName);
    }

    private void autoFillTwo() {
        Intent i = getIntent();
        String cardNo = i.getStringExtra(UCProtocolKey.KEY_CARDNUM);
        mCardNo.setText(cardNo);

        String subBankCode = i.getStringExtra(UCProtocolKey.KEY_SUBBANKCODE);
        String subBankName = i.getStringExtra(UCProtocolKey.KEY_SUBBANKNAME);
        String provinceId = i.getStringExtra(UCProtocolKey.KEY_PROVIVCEID);
        String provinceName = i.getStringExtra(UCProtocolKey.KEY_PROVINCENAME);
        String areaId = i.getStringExtra(UCProtocolKey.KEY_AREAID);
        String areaName = i.getStringExtra(UCProtocolKey.KEY_AREANAME);

        if (!TextUtils.isEmpty(subBankCode) && !TextUtils.isEmpty(subBankName)) {
            mSubSelectedBank = new Bank();
            mSubSelectedBank.setBankCode(subBankCode);
            mSubSelectedBank.setBankName(subBankName);
            mSubBank.setText(subBankName);
        }
        if (!TextUtils.isEmpty(provinceId) && !TextUtils.isEmpty(provinceName)) {
            HPLog.e("autoFill", "provinceId:" + provinceId);
            mBankProvince = new BankProvince();
            mBankProvince.setBankProvinceId(provinceId);
            mBankProvince.setBankProvinceName(provinceName);
            i.putExtra(KEY_BANKPROVINCENAME_BACKUP, provinceName);
        }

        HPLog.e("autoFill", "areaId:" + areaId);
        if (!TextUtils.isEmpty(areaId) && !TextUtils.isEmpty(areaName)) {
            mSelectBankArea = new BankArea();
            mSelectBankArea.setBankAreaId(Integer.parseInt(areaId));
            mSelectBankArea.setBankAreaName(areaName);
            mAreaFlag.setText(areaName);
        }
        i.putExtra(KEY_BANKAREA_BACKUP, areaName);
        i.putExtra(KEY_BANKNAME_BACKUP, i.getStringExtra(UCProtocolKey.KEY_BANKNAME));
    }

    private void cleanBankInfo() {
        mCardNo.setText("");
        mSubSelectedBank = new Bank();
        mSubBank.setText("");
        mBankProvince = new BankProvince();
        mSelectBankArea = new BankArea();
        mAreaFlag.setText("");
    }

    /**
     * 检查用户填入的数据是否正确。
     *
     * @return 返回为正确，表示填写的数据没有问题
     */
    private boolean checkField() {
        // 检查用户名的是否符合要求
        String userName = mName.getText().toString().trim();
        if (!CommonUtils.isRealName(userName)) {
            Toast.makeText(this, R.string.input_right_user_name_tip, Toast.LENGTH_SHORT).show();
            return false;
        }
        // 检查身份证是否符合要求
        String idNo = mCertNo.getText().toString().trim();
        try {
            if (CommonUtils.IDCardValidate(idNo, true) != null) {
                Toast.makeText(this, R.string.input_right_id_no_tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 检查商店名
        String shopName = mShopName.getText().toString();
        if (TextUtils.isEmpty(shopName)) {
            Toast.makeText(this, R.string.input_shop_name_tip_please, Toast.LENGTH_SHORT).show();
            return false;
        } else {
            if (!CommonUtils.isShopNameLegal(shopName)) {
                Toast.makeText(this, R.string.input_right_shop_name_tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 检查收款行
        if (null == mMainBank || "-1".equals(mMainBank.getBankCode())) {
            Toast.makeText(this, R.string.select_bank_tip, Toast.LENGTH_SHORT).show();
            return false;
        }
        // 检查省份
        if ("1".equals(mMainBank.getProvinceFlag())) {
            if (null == mBankProvince || TextUtils.isEmpty(mBankProvince.getBankProvinceId())) {
                Toast.makeText(this, R.string.select_bankProvince_tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 检查地市
        if ("1".equals(mMainBank.getAreaFlag()) && null == mSelectBankArea) {
            if (TextUtils.isEmpty(mAreaFlag.getText().toString())) {
                Toast.makeText(this, R.string.select_bankArea_tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 检查收款支行/开户行
        if ("1".equals(mMainBank.getSubBankFlag()) && null == mSubSelectedBank) {
            if (TextUtils.isEmpty(this.mSubBank.getText().toString())) {
                // mSubBank.requestFocus();
                Toast.makeText(this, R.string.select_sub_bank_tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 检查银行卡号
        String cardNo = this.mCardNo.getText().toString();
        cardNo = cardNo.replace(" ", "");
        if (!CommonUtils.isLegalCard(cardNo)) {
            Toast.makeText(this, R.string.input_right_card_no_tip, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (0 == mMainAdapter.getCount()) {
            this.queryMainBankList(true);
        } else {
            requestCurrentLocation(true);
        }
    }

    @Override
    public void onBanksLoad(List<Bank> banks) {
        requestCurrentLocation(true);
        String bankCode = getIntent().getStringExtra(UCProtocolKey.KEY_BANKCODE);
        mMainAdapter.refreshBanks(banks);
        mMainSpinner.setAdapter(mMainAdapter);
        // 如果传入数据进来。找到之前选中的那个。
        if (!TextUtils.isEmpty(bankCode)) {
            int i;
            for (i = 0; i < banks.size(); i++) {
                if (banks.get(i).getBankCode().equals(bankCode)) {
                    break;
                }
            }
            if (i == banks.size()) {
                i = 0;
                cleanBankInfo();
            } else {

                autoFillTwo();
            }
            mMainBank = banks.get(i);
            mMainSpinner.setSelection(i);
            getIntent().putExtra(UCProtocolKey.KEY_BANKCODE, "");
        } else {
            mMainSpinner.setSelection(mMainAdapter.getCount());
        }
    }

    @Override
    public void onSubBanksLoad(List<Bank> banks) {
        mSubBank.refreshBanks(banks);
    }

    @Override
    public void onBankProvincesLoad(List<BankProvince> province) {
        requestCurrentLocation(true);
        String bankProvinceId = getIntent().getStringExtra(UCProtocolKey.KEY_PROVIVCEID);
        mProvinceAdapter.refreshBankProvinces(province);
        mProvincesFlagSpinner.setAdapter(mProvinceAdapter);
        if (!TextUtils.isEmpty(bankProvinceId)) {
            int j;
            for (j = 0; j < province.size(); j++) {
                if (String.valueOf(province.get(j).getBankProvinceId()).equals(bankProvinceId)) {
                    break;
                }
            }
            if (j == province.size()) {
                j = 0;
            }
            mBankProvince = province.get(j);
            mProvincesFlagSpinner.setSelection(j);
            getIntent().putExtra(UCProtocolKey.KEY_PROVIVCEID, "");
            getIntent().putExtra(UCProtocolKey.KEY_PROVINCENAME, "");
        } else {
            mProvincesFlagSpinner.setSelection(mProvinceAdapter.getCount());
        }

    }

    @Override
    public void onBankAreaLoad(List<BankArea> area) {
        mAreaFlag.refreshBankArea(area);
    }

    @Override
    public void onBankSelected(Bank b) {
        // 在用户选中的瞬间，是不用去搜索的。所以先去掉监听，设置完成后，再加入监听。
        mSubBank.removeTextChangedListener(mTextWatch);
        if (null != b) {
            this.mSubSelectedBank = b;
            mSubBank.setText(b.getBankName());
        } else {
            this.mSubSelectedBank = null;
            mSubBank.setText("");
        }
        mSubBank.addTextChangedListener(mTextWatch);
    }

    @Override
    protected void goBack() {
        Intent i = getIntent();
        boolean fromReg = i.getBooleanExtra(RegisterResultActivity.FROM_REG_RESULT, false);
        if (fromReg) {
            // 如果是第一次注册成功，直接提交资料，返回回到账户界面
            onAccountTab(null);
        } else {
            super.goBack();
        }
    }

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */

    private boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.NUMBER_FORMS || ub == Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS || ub == Character.UnicodeBlock.MATHEMATICAL_OPERATORS || ub == Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL || ub == Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS || ub == Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A || ub == Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B || ub == Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS;
    }

    /**
     * 检测String是否全是中文
     *
     * @param name
     * @return
     */
    private boolean checkNameChese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    @Override
    public void onBankAreaSelected(BankArea province) {
        // 在用户选中的瞬间，是不用去搜索的。所以先去掉监听，设置完成后，再加入监听。
        mAreaFlag.removeTextChangedListener(mBankAreaTextWatch);
        if (null != province) {
            this.mSelectBankArea = province;
            mAreaFlag.setText(province.getBankAreaName());
        } else {
            this.mSelectBankArea = null;
            mAreaFlag.setText("");
        }
        mAreaFlag.addTextChangedListener(mBankAreaTextWatch);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_CARD == requestCode) {
            if (RESULT_OK == resultCode && null != data) {
                mCardNo.setText(data.getStringExtra(BaseProtocolKey.ACCOUNT));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    // 字母正则验证
    private boolean isLetter(String text) {
        Pattern p = Pattern.compile("[a-zA-Z]");
        Matcher m = p.matcher(text);
        return m.matches();
    }

    // 数字正则验证
    private boolean isNumble(String text) {
        Pattern p = Pattern.compile("[0-9]");
        Matcher m = p.matcher(text);
        return m.matches();
    }

    // 是否是汉字
    private boolean ischainse(String text) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(text);
        return m.matches();
    }

    @Override
    public void goToVPos() {
        super.goToVPos();
        if (checkSwiperOk(BaseInfoEditorActivity.this, true)) {
            if (swiperType == ZZTConstant.SWIPER_GOTO_SWIPERCARD) {
                Intent intent = new Intent(BaseInfoEditorActivity.this, SwipeCard.class);
                startActivityForResult(intent, REQUEST_CARD);
            }
        }
    }

}
